package com.ruoyi.web.controller.net;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.net.domain.*;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.*;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 业务-mplstp配置Controller
 *
 * @author net
 * @date 2024-11-26
 */
@Api(tags = "业务-mplstp配置")
@RestController
@RequestMapping("/busi/mplstp")
public class BusiMplstpController extends BaseController {
    @Autowired
    private IBusiMplstpService busiMplstpService;
    @Autowired
    private IBusiElementStatusService busiElementStatusService;
    @Autowired
    private DeviceManager deviceManager;

    @Autowired
    private INetElementService netElementService;
    @Autowired
    private IBusiMplstpRouteTableService busiMplstpRouteTableService;

    @Autowired
    private IElementPortEthService elementPortEthService;

    @Autowired
    private IElementPortModeService elementPortModeService;
    @Autowired
    IElementBusiMplsAlarmoamService elementBusiMplsAlarmoamService;
    @Autowired
    IBusiMplstpElementService busiMplstpElementService;
    /**
     * 查询业务-mplstp配置列表
     */
    @ApiOperation(value = "查询业务-mplstp配置列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:mplstp:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusiMplstp busiMplstp) {
        startPage();
        List<BusiMplstpListVo> list = busiMplstpService.selectBusiMplstpList(busiMplstp);
        return getDataTable(list);
    }

    /**
     * 查询业务-mplstp配置列表
     */
    @ApiOperation(value = "查询网元-业务-mplstp列表", httpMethod = "GET")
//    @PreAuthorize("@ss.hasPermi('net:mplstp:list')")
    @GetMapping("/ele/list")
    public TableDataInfo eleList(BusiMplstpListVo busiMplstp) {
        startPage();
        List<BusiMplstpListVo2> list = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);
//        List<BusiMplstpListVo> list = busiMplstpService.selectBusiMplstpEleList(busiMplstp);
        return getDataTable(list);
    }

    /**
     * 导出业务-mplstp配置列表
     */
    @ApiOperation(value = "导出业务-mplstp配置列表", httpMethod = "POST")
    @PreAuthorize("@ss.hasPermi('net:mplstp:export')")
    @Log(title = "业务-mplstp配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusiMplstp busiMplstp) {
        List<BusiMplstpListVo> list = busiMplstpService.selectBusiMplstpList(busiMplstp);
        ExcelUtil<BusiMplstpListVo> util = new ExcelUtil<>(BusiMplstpListVo.class);
        util.exportExcel(response, list, "业务-mplstp配置数据");
    }

    /**
     * 获取业务-mplstp配置详细信息
     */
    @ApiOperation(value = "获取业务-mplstp配置详细信息", httpMethod = "GET")
    @PreAuthorize("@ss.hasPermi('net:mplstp:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(busiMplstpService.selectBusiMplstpById(id));
    }

    /**
     * 新增业务-mplstp配置
     */
    @ApiOperation(value = "新增业务-mplstp配置", httpMethod = "POST")
    @PreAuthorize("@ss.hasPermi('net:mplstp:add')")
    @Log(title = "业务-mplstp配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusiMplstpVo busiMplstpVo) {
        return toAjax(busiMplstpService.insertBusiMplstp(busiMplstpVo));
//
    }

    /**
     * 修改业务-mplstp配置
     */
    @ApiOperation(value = "修改业务-mplstp配置", httpMethod = "PUT")
    @PreAuthorize("@ss.hasPermi('net:mplstp:edit')")
    @Log(title = "业务-mplstp配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusiMplstp busiMplstp) {
        return toAjax(busiMplstpService.updateBusiMplstp(busiMplstp));
    }

    /**
     * 删除业务-mplstp配置
     */
    @ApiOperation(value = "删除业务-mplstp配置", httpMethod = "DELETE")
    @PreAuthorize("@ss.hasPermi('net:mplstp:remove')")
    @Log(title = "业务-mplstp配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(busiMplstpService.deleteBusiMplstpByIds(ids));
    }

    @ApiOperation(value = "点击'完成'按钮更新业务-mplstp配置状态", httpMethod = "PUT")
    @PreAuthorize("@ss.hasPermi('net:mplstp:edit')")
    @Log(title = "业务-mplstp配置", businessType = BusinessType.UPDATE)
    @PutMapping("/complete")
    public AjaxResult complete(@RequestBody BusiMplstp busiMplstp) {
        return toAjax(busiMplstpService.updateBusiMplstpStatus(busiMplstp));
    }

    /**
     * 批量激活设备
     *
     * @param
     */
    @ApiOperation(value = "业务管理界面批量激活设备", httpMethod = "GET")
    @GetMapping(value = "/activateAll/{mplsId}")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult activateDeviceAll(@PathVariable("mplsId") String mplsId) {
        BusiElementStatus busiElementStatus = new BusiElementStatus();
        busiElementStatus.setBusiId(mplsId);
        List<BusiElementStatus> statusList = busiElementStatusService.selectBusiElementStatusList(busiElementStatus);
        return toAjax(batchActivate(statusList, mplsId));
    }

    /**
     * 批量激活
     * @param statusListParam
     * @param mplsId
     * @return
     */
    private int batchActivate(List<BusiElementStatus> statusListParam,String mplsId) {
        int result = 0;
//        try {
            for (BusiElementStatus busiElementStatusParam : statusListParam) {
                String elementId = busiElementStatusParam.getElementId();
                BusiMplstpListVo busiMplstp = new BusiMplstpListVo();
                busiMplstp.setElementId(elementId);
                List<BusiMplstpListVo2> list = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);
                List<BusiMplstpListVo2> collect = list.stream().filter(e -> e.getMplstpId().equals(mplsId)).collect(Collectors.toList());
                collect.get(0).setStatus("1");
                if (sendXml(collect.get(0), elementId)) {
                    busiMplstp.setStatus("1");
                    busiMplstp.setElementId(null);
                    busiMplstp.setId(collect.get(0).getMplstpId());
                    //同步业务设备网元状态
                    BusiElementStatus busiElementStatus = new BusiElementStatus();
                    busiElementStatus.setElementId(elementId);
                    busiElementStatus.setBusiId(collect.get(0).getMplstpId());
                    busiElementStatus.setStatus("1");
                    busiElementStatus.setUpdateBy(SecurityUtils.getUsername());
                    busiElementStatus.setUpdateTime(DateUtils.getNowDate());
                    busiElementStatusService.updateBusiElementStatusByParams(busiElementStatus);
                    //更新单站业务表状态
                    BusiMplstpElement busiMplstpElement = new BusiMplstpElement();
                    busiMplstpElement.setMplstpId(collect.get(0).getMplstpId());
                    busiMplstpElement.setElementId(elementId);
                    busiMplstpElement.setStatus("1");
                    busiMplstpElementService.updateBusiMplstpElementByParam(busiMplstpElement);
                    //更新业务表状态  部分激活2/激活1
                    BusiElementStatus busiElementStatus1 = new BusiElementStatus();
                    busiElementStatus1.setBusiId(collect.get(0).getMplstpId());
                    List<BusiElementStatus> statusList = busiElementStatusService.selectBusiElementStatusList(busiElementStatus1);
                    Optional<BusiElementStatus> max = statusList.stream().max(Comparator.comparing(BusiElementStatus::getStatus));
                    Optional<BusiElementStatus> min = statusList.stream().min(Comparator.comparing(BusiElementStatus::getStatus));
                    if (max.get().getStatus().equals(min.get().getStatus())){
                        if ("0".equals(max.get().getStatus())){
                            busiMplstp.setStatus("0");
                        }else {
                            busiMplstp.setStatus("1");
                        }
                    }else {
                        busiMplstp.setStatus("2");
                    }
                    result = busiMplstpService.updateBusiMplstp(busiMplstp);
                } else {
                    logger.info("mplsp-业务管理批量激活-单站激活失败");
                }
            }
//        } catch (Exception e) {
//            throw new RuntimeException("批量激活异常",e);
//        }
        return result;
    }

    /**
     * 批量去激活设备
     *
     * @param
     */
    @ApiOperation(value = "业务管理界面批量去激活设备", httpMethod = "GET")
    @GetMapping(value = "/unactivateAll/{mplsId}")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult unactivateDeviceAll(@PathVariable("mplsId") String mplsId) {
        BusiElementStatus busiElementStatus = new BusiElementStatus();
        busiElementStatus.setBusiId(mplsId);
        List<BusiElementStatus> statusList = busiElementStatusService.selectBusiElementStatusList(busiElementStatus);
        return toAjax(batchUnActivate(statusList, mplsId));
    }

    /**
     * 批量去激活设备
     * @param statusListParam
     * @param mplsId
     * @return
     */
    private int batchUnActivate(List<BusiElementStatus> statusListParam, String mplsId) {
        int result = 0;
//        try {
            for (BusiElementStatus busiElementStatusParam : statusListParam) {
                String elementId= busiElementStatusParam.getElementId();
                BusiMplstpListVo busiMplstp = new BusiMplstpListVo();
                busiMplstp.setElementId(elementId);
                List<BusiMplstpListVo2> list = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);
                List<BusiMplstpListVo2> collect = list.stream().filter(e -> e.getMplstpId().equals(mplsId)).collect(Collectors.toList());
                collect.get(0).setStatus("0");
                if (sendXml(collect.get(0), elementId)) {
                    busiMplstp.setId(collect.get(0).getMplstpId());
                    //同步业务设备网元状态
                    BusiElementStatus busiElementStatus = new BusiElementStatus();
                    busiElementStatus.setElementId(elementId);
                    busiElementStatus.setBusiId(collect.get(0).getMplstpId());
                    busiElementStatus.setStatus("0");
                    busiElementStatus.setUpdateBy(SecurityUtils.getUsername());
                    busiElementStatus.setUpdateTime(DateUtils.getNowDate());
                    busiElementStatusService.updateBusiElementStatusByParams(busiElementStatus);
                    //更新单站业务表状态
                    BusiMplstpElement busiMplstpElement = new BusiMplstpElement();
                    //两个一起去激活
                    busiMplstpElement.setMplstpId(collect.get(0).getMplstpId());
                    busiMplstpElement.setElementId(elementId);
                    busiMplstpElement.setStatus("0");
                    busiMplstpElementService.updateBusiMplstpElementByParam(busiMplstpElement);
                    BusiElementStatus busiElementStatus1 = new BusiElementStatus();
                    //更新业务表状态  部分激活2/未激活0
                    busiElementStatus1.setBusiId(collect.get(0).getMplstpId());
                    List<BusiElementStatus> statusList = busiElementStatusService.selectBusiElementStatusList(busiElementStatus1);
                    Optional<BusiElementStatus> max = statusList.stream().max(Comparator.comparing(BusiElementStatus::getStatus));
                    Optional<BusiElementStatus> min = statusList.stream().min(Comparator.comparing(BusiElementStatus::getStatus));
                    if (max.get().getStatus().equals(min.get().getStatus())){
                        if ("0".equals(max.get().getStatus())){
                            busiMplstp.setStatus("0");
                        }else {
                            busiMplstp.setStatus("1");
                        }
                    }else {
                        busiMplstp.setStatus("2");
                    }
                    result = busiMplstpService.updateBusiMplstp(busiMplstp);
                } else {
                    logger.info("mplsp-业务管理批量去激活-单站去激活失败");
                }
            }
//        } catch (Exception e) {
//            throw new RuntimeException("批量去激活异常",e);
//        }
        return result;
    }

    /**
     * 激活设备
     * @param mplsId 单站业务id
     * @param
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{mplsId}/{elementId}")
    @Log(title = "激活设备", businessType = BusinessType.UPDATE)
    public AjaxResult activateDevice(@PathVariable("mplsId") String mplsId, @PathVariable("elementId") String elementId) {
        BusiMplstpListVo busiMplstp = new BusiMplstpListVo();
        busiMplstp.setElementId(elementId);
        List<BusiMplstpListVo2> list = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);

        List<BusiMplstpListVo2> collect = list.stream().filter(e -> e.getId().equals(mplsId)).collect(Collectors.toList());
        collect.get(0).setStatus("1");
        if (sendXml(collect.get(0), elementId)) {
            busiMplstp.setStatus("1");
            busiMplstp.setElementId(null);
            busiMplstp.setId(collect.get(0).getMplstpId());
            //同步业务设备网元状态
            BusiElementStatus busiElementStatus = new BusiElementStatus();
            busiElementStatus.setElementId(elementId);
            busiElementStatus.setBusiId(collect.get(0).getMplstpId());
            busiElementStatus.setStatus("1");
            busiElementStatus.setUpdateBy(SecurityUtils.getUsername());
            busiElementStatus.setUpdateTime(DateUtils.getNowDate());
            busiElementStatusService.updateBusiElementStatusByParams(busiElementStatus);
            //更新单站业务表状态
            BusiMplstpElement busiMplstpElement = new BusiMplstpElement();
            busiMplstpElement.setMplstpId(collect.get(0).getMplstpId());
            busiMplstpElement.setElementId(elementId);
            busiMplstpElement.setStatus("1");
            busiMplstpElementService.updateBusiMplstpElementByParam(busiMplstpElement);
            BusiElementStatus busiElementStatus1 = new BusiElementStatus();
            //更新业务表状态  部分激活2/激活1
            busiElementStatus1.setBusiId(collect.get(0).getMplstpId());
            List<BusiElementStatus> statusList = busiElementStatusService.selectBusiElementStatusList(busiElementStatus1);
            Optional<BusiElementStatus> max = statusList.stream().max(Comparator.comparing(BusiElementStatus::getStatus));
            Optional<BusiElementStatus> min = statusList.stream().min(Comparator.comparing(BusiElementStatus::getStatus));
            if (max.get().getStatus().equals(min.get().getStatus())){
                if ("0".equals(max.get().getStatus())){
                    busiMplstp.setStatus("0");
                }else {
                    busiMplstp.setStatus("1");
                }
            }else {
                busiMplstp.setStatus("2");

            }
            return toAjax(busiMplstpService.updateBusiMplstp(busiMplstp));
        } else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @Log(title = "去激活设备", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/unactivate/{mplsId}/{elementId}")
    public AjaxResult unactivateDevice(@PathVariable("mplsId") String mplsId, @PathVariable("elementId") String elementId) {
        BusiMplstpListVo busiMplstp = new BusiMplstpListVo();
        busiMplstp.setElementId(elementId);
        List<BusiMplstpListVo2> list = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);
        List<BusiMplstpListVo2> collect = list.stream().filter(e -> e.getId().equals(mplsId)).collect(Collectors.toList());
        collect.get(0).setStatus("0");
        if (sendXml(collect.get(0), elementId)) {
            busiMplstp.setId(collect.get(0).getMplstpId());
            //同步业务设备网元状态
            BusiElementStatus busiElementStatus = new BusiElementStatus();
            busiElementStatus.setElementId(elementId);
            busiElementStatus.setBusiId(collect.get(0).getMplstpId());
            busiElementStatus.setStatus("0");
            busiElementStatus.setUpdateBy(SecurityUtils.getUsername());
            busiElementStatus.setUpdateTime(DateUtils.getNowDate());
            busiElementStatusService.updateBusiElementStatusByParams(busiElementStatus);
            //更新单站业务表状态
            BusiMplstpElement busiMplstpElement = new BusiMplstpElement();
            //两个一起去激活
            busiMplstpElement.setMplstpId(collect.get(0).getMplstpId());
            busiMplstpElement.setElementId(elementId);
            busiMplstpElement.setStatus("0");
            busiMplstpElementService.updateBusiMplstpElementByParam(busiMplstpElement);
            BusiElementStatus busiElementStatus1 = new BusiElementStatus();
            //更新业务表状态  部分激活2/未激活0
            busiElementStatus1.setBusiId(collect.get(0).getMplstpId());
            List<BusiElementStatus> statusList = busiElementStatusService.selectBusiElementStatusList(busiElementStatus1);
            Optional<BusiElementStatus> max = statusList.stream().max(Comparator.comparing(BusiElementStatus::getStatus));
            Optional<BusiElementStatus> min = statusList.stream().min(Comparator.comparing(BusiElementStatus::getStatus));
            if (max.get().getStatus().equals(min.get().getStatus())){
                if ("0".equals(max.get().getStatus())){
                    busiMplstp.setStatus("0");
                }else {
                    busiMplstp.setStatus("1");
                }
            }else {
                busiMplstp.setStatus("2");
            }
            return toAjax(busiMplstpService.updateBusiMplstp(busiMplstp));
        } else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(BusiMplstpListVo2 entity, String elementId) {

        // TODO: 2024/11/22 待与设备联调
        NetElement netElement = netElementService.getCacheObject(elementId);
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            if ("无保护".equals(entity.getProtectType())) {
                return sendNoProtectXml(entity, elementId);
            } else {
                return sendProtectXml(entity, elementId);
            }
        }
        return false;
    }

    /**
     * 下发有保护报文
     *
     * @param entity
     * @param elementId
     * @return
     */
    private boolean sendProtectXml(BusiMplstpListVo2 entity, String elementId) {
        BusiMplsXmlVo busiMplsXmlVo = new BusiMplsXmlVo();
        boolean isSend = true;
        //源网元只有对应出信息  前后端达成一致   start为入  end为出
        if ("1".equals(entity.getElementType())) {
            busiMplsXmlVo.setElementId(entity.getStartElement());
            busiMplsXmlVo.setPortName(entity.getPositiveEndPortName());
            busiMplsXmlVo.setInLabel(entity.getReverseStartLabel());
            busiMplsXmlVo.setOutLabel(entity.getPositiveEndLabel());
            busiMplsXmlVo.setDestIp(entity.getEndLsrId().substring(entity.getEndLsrId().indexOf("(") + 1, entity.getEndLsrId().indexOf(")")));
        } else if ("2".equals(entity.getElementType())) {
            busiMplsXmlVo.setElementId(entity.getEndElement());
            busiMplsXmlVo.setPortName(entity.getPositiveStartPortName());
            busiMplsXmlVo.setInLabel(entity.getPositiveStartLabel());
            busiMplsXmlVo.setOutLabel(entity.getReverseEndLabel());
            busiMplsXmlVo.setDestIp(entity.getStartLsrId().substring(entity.getStartLsrId().indexOf("(") + 1, entity.getStartLsrId().indexOf(")")));

        } else if ("3".equals(entity.getElementType())) {
            boolean crossIsSend = true;
            //过站 激活 去激活
            BusiMplstpListVo busiMplstp = new BusiMplstpListVo();
            busiMplstp.setElementId(elementId);
            busiMplstp.setId(entity.getMplstpId());
            List<BusiMplstpListVo2> listByElement = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);
            //正常就两条数据  工作  保护
            for (BusiMplstpListVo2 busiMplstpElement : listByElement) {
                String lspName = "";
                if ("1".equals(busiMplstpElement.getRouteType())){
                    //工作的正向
                    lspName = busiMplstpElement.getPositiveLspName();
                }else {
                    //保护的反向
                    lspName = busiMplstpElement.getReverseLspName();
                }
                //激活
                if ("1".equals(entity.getStatus())) {
                    //出接口的IP和下一跳是同一个网段  连纤两端的IP必须在一个网段？？？前端限制
                    String actCrossXml = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                            "        <static-te-lsps>" +
                            "          <static-te-lsp>" +
                            "            <lsp-name>" + lspName + "</lsp-name>" +//与555行值一致  导致报错
                            "            <lsp-role>bi-transit</lsp-role>" +
                            "            <bi-lsp-type>bi</bi-lsp-type>" +
                            "            <out-segment>" +
                            "              <next-hop>" + busiMplstpElement.getPositiveIp() + "</next-hop>" +
                            "              <out-label>"+busiMplstpElement.getPositiveEndLabel()+"</out-label>" ;
                            if(!busiMplstpElement.getPositiveEndPortName().startsWith("mtnveth")){
                                actCrossXml+="              <out-ifname>" + busiMplstpElement.getPositiveEndPortName() + "</out-ifname>" ;
                            }else{
                                String mtnNum = busiMplstpElement.getPositiveEndPortName().split("mtnveth")[1];
                                actCrossXml+="              <out-ifname>flexe-tunnel" + mtnNum + "</out-ifname>" ;
                            }

                    actCrossXml+="            </out-segment>" +
                            "            <in-segment>" +
                            "              <in-label>"+busiMplstpElement.getPositiveStartLabel()+"</in-label>" ;
                            if(!busiMplstpElement.getPositiveStartPortName().startsWith("mtnveth")){
                                actCrossXml+="              <in-ifname>" + busiMplstpElement.getPositiveStartPortName() + "</in-ifname>" ;
                            }else{
                                String mtnNum = busiMplstpElement.getPositiveStartPortName().split("mtnveth")[1];
                                actCrossXml+="              <in-ifname>flexe-tunnel" + mtnNum + "</in-ifname>" ;
                            }

                    actCrossXml+="            </in-segment>" +
                            "            <reverse-in-segment>" +
                            "              <in-label>"+busiMplstpElement.getReverseStartLabel()+"</in-label>" ;
                            if(!busiMplstpElement.getReverseStartPortName().startsWith("mtnveth")){
                                actCrossXml+= "              <in-ifname>" + busiMplstpElement.getReverseStartPortName() + "</in-ifname>" ;
                            }else{
                                String mtnNum = busiMplstpElement.getReverseStartPortName().split("mtnveth")[1];
                                actCrossXml+="              <in-ifname>flexe-tunnel" + mtnNum + "</in-ifname>" ;
                            }

                    actCrossXml+="            </reverse-in-segment>" +
                            "            <reverse-out-segment>" +
                            "              <next-hop>" + busiMplstpElement.getReverseIp() + "</next-hop>" +
                            "              <out-label>"+busiMplstpElement.getReverseEndLabel()+"</out-label>" ;
                            if(!busiMplstpElement.getReverseEndPortName().startsWith("mtnveth")){
                                actCrossXml+= "              <out-ifname>" + busiMplstpElement.getReverseEndPortName() + "</out-ifname>" ;
                            }else{
                                String mtnNum = busiMplstpElement.getReverseEndPortName().split("mtnveth")[1];
                                actCrossXml+="              <out-ifname>flexe-tunnel" + mtnNum + "</out-ifname>" ;
                            }

                    actCrossXml+="            </reverse-out-segment>" +
                            "          </static-te-lsp>" +
                            "        </static-te-lsps>" +
                            "        <mpls-te/>" +
                            "      </mpls>";
                    logger.info("mplsp-过站激活报文数据actCrossXml：" + actCrossXml.toString());

                    crossIsSend = deviceManager.editConfig(actCrossXml, "merge");
                    logger.info("mplsp-过站激活报文数据actCrossXml执行结果=========================================="+crossIsSend);

                } else {
                    //去激活
                    String unActCrossXml = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                            "        <static-te-lsps>" +
                            "          <static-te-lsp nc:operation=\"remove\">" +
                            "            <lsp-name>" + lspName + "</lsp-name>" +
                            "            <lsp-role>bi-transit</lsp-role>" +//过站transit  源宿head
                            "            <bi-lsp-type>bi</bi-lsp-type>" +
                            "          </static-te-lsp>" +
                            "        </static-te-lsps>" +
                            "        <mpls-te/>" +
                            "      </mpls>";
                    logger.info("mplsp-过站去激活报文数据unActCrossXml：" + unActCrossXml.toString());
                    crossIsSend = deviceManager.editConfig(unActCrossXml, "merge");
                    logger.info("mplsp-过站去激活报文数据unActCrossXml执行结果=========================================="+crossIsSend);
                }
            }
            return crossIsSend;
        }
        //查询 ip mask
        ElementPortEth elementPortEth = new ElementPortEth();
        elementPortEth.setElementId(busiMplsXmlVo.getElementId());
        elementPortEth.setPortName(busiMplsXmlVo.getPortName());
        List<ElementPortEth> elementPortEths = elementPortEthService.selectElementPortEthList(elementPortEth);
        if (!CollectionUtils.isEmpty(elementPortEths)) {
            busiMplsXmlVo.setIp(elementPortEths.get(0).getIp());
            busiMplsXmlVo.setMask(elementPortEths.get(0).getMask());
            busiMplsXmlVo.setMaxFrameLen(elementPortEths.get(0).getMaxFrameLen());

        }
        //前后端达成一致   start为入  end为出
        //1对于源网元，只有源端口源标签，有正向下一跳地址，无反向下一跳地址；出端口、出标签从路由表中获取
        //2对于宿网元，只有宿端口宿标签，无正向下一跳地址，有反向下一跳地址；出端口、出标签从路由表中获取
        //查询下一跳地址
        if ("1".equals(entity.getElementType())) {
            busiMplsXmlVo.setNextIp(entity.getPositiveIp());
        } else if ("2".equals(entity.getElementType())) {
            busiMplsXmlVo.setNextIp(entity.getReverseIp());
        }
        //激活
        if ("1".equals(entity.getStatus())){
            return sendProtectActXml(entity,elementId,busiMplsXmlVo);
        }else {
            //去激活
            return sendProtectInactXml(entity,elementId,busiMplsXmlVo);
        }
    }
    /**
     * 下发源宿有保护-激活报文
     * @param entity
     */
    private boolean sendProtectActXml(BusiMplstpListVo2 entity,String elementId,BusiMplsXmlVo busiMplsXmlVo) {
        //==========================================================查询oam信息========================
        ElementBusiMplsAlarmoam oamParam = new ElementBusiMplsAlarmoam();
        oamParam.setMplstpId(entity.getMplstpId());
        //网元id
        oamParam.setElementId(elementId);
        //正常结果2条
        List<ElementBusiMplsAlarmoamVo> oamList = elementBusiMplsAlarmoamService.selectElementBusiMplsAlarmoamList(oamParam);
        boolean isSend = true;
        String workMeName = "";
        String proMeName = "";

        for (ElementBusiMplsAlarmoam oam :oamList){
            if ("1".equals(oam.getRouteType())){
                workMeName = oam.getMeName();
            }else{
                proMeName = oam.getMeName();
            }
            String[] meg = oam.getMeg().split("/");
            String oamXml ="<tpoam xmlns=\"http://fiberhome.com/fhnw/yang/oam/fos-tpoam\">" +
                    "        <meg-cfg>" +
                    "          <meg-list>" +
                    "            <meg-name>"+oam.getMegName()+"</meg-name>" +
                    "            <level>" + meg[4] + "</level>" +
                    "            <icc>" + meg[0] + "</icc>" +
                    "            <umc>" + meg[1] + "</umc>" +
                    "            <me-list>" +
                    "              <me-name>"+oam.getMeName()+"</me-name>" +
                    "              <mep-id>"+meg[2]+"</mep-id>" +
                    "              <remote-mep-id>"+meg[3]+"</remote-mep-id>" +//插入时数据已对应
                    "              <mp-type>mep</mp-type>" +
                    "              <ccm-send-enable>enable</ccm-send-enable>" +
                    "              <ccm-interval>"+oam.getCv().replace(".","_")+"</ccm-interval>" +
                    "              <aps-send-enable>enable</aps-send-enable>" +
                    "              <fdi-send-enable>disable</fdi-send-enable>" +
                    "              <csf-send-enable>disable</csf-send-enable>" +
                    "              <oam-exp>"+oam.getLspTtl().split("/")[1]+"</oam-exp>" +
                    "              <oam-ttl>"+oam.getLspTtl().split("/")[0]+"</oam-ttl>" +
                    "              <dual-lm-enable>disable</dual-lm-enable>" +
                    "            </me-list>" +
                    "          </meg-list>" +
                    "        </meg-cfg>" +
                    "      </tpoam>";
            logger.info("mplsp-oam报文数据protectActiveXml1：" + oamXml.toString());
            isSend = deviceManager.editConfig(oamXml, "merge");
            logger.info("mplsp-报文数据protectActiveXml1执行结果=========================================="+isSend);
        }
        //==========================================================查询tunnel信息========================

        BusiMplstpElement busiMplstpElement = new BusiMplstpElement();
        busiMplstpElement.setMplstpId(entity.getMplstpId());
        busiMplstpElement.setElementId(elementId);
        //正常结果工作、保护2条
        List<BusiMplstpElement> busiMplstpElements = busiMplstpElementService.selectBusiMplstpElementList(busiMplstpElement);
        for (BusiMplstpElement busiMplstpElement1 : busiMplstpElements){
            String  tunnelXml =" <if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                    "   <interfaces>" +
                    "     <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                    "    <name>tunnel"+busiMplstpElement1.getPositiveTunnelId()+"</name>" +
                    "    <type>TUNNEL</type>" +
                    "     </interface>" +
                    "   </interfaces>" +
                    "    </if>";
            logger.info("mplsp-tunnel报文数据tunnelXml：" + tunnelXml.toString());
            isSend = deviceManager.editConfig(tunnelXml, "merge");
            logger.info("mplsp-tunnel报文数据protectActiveXml2执行结果=========================================="+isSend);
        }
        //==========================================================查询lsp 出入端口、标签信息========================
        BusiMplstpListVo busiMplstp = new BusiMplstpListVo();
        busiMplstp.setElementId(elementId);
        busiMplstp.setId(entity.getMplstpId());
        List<BusiMplstpListVo2> listByElement = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);
        //过滤两条数据  工作  保护
        for (BusiMplstpListVo2 busiMplstpElement1 : listByElement){
            String lspName = "";
            String ip = "";
            String outLable = "";
            String inLable = "";
            String outName = "";
            String inName = "";
            //工作
            if ("1".equals(busiMplstpElement1.getRouteType())){
                lspName = busiMplstpElement1.getPositiveLspName();
            }else {
                lspName = busiMplstpElement1.getReverseLspName();
            }

            //源 只有出端口、出标签 反向入端口  反向入标签，正向下一跳地址
            if ("1".equals(entity.getElementType())){
                ip = busiMplstpElement1.getPositiveIp();
                outLable = busiMplstpElement1.getPositiveEndLabel();
                inLable = busiMplstpElement1.getReverseStartLabel();
                if (!"veth".equals(busiMplstpElement1.getPortMode())){
                    outName = busiMplstpElement1.getPositiveEndPortName();
                    inName = busiMplstpElement1.getReverseStartPortName();
                }else {
                    outName = "flexe-tunnel"+busiMplstpElement1.getPositiveEndPortName().split("mtnveth")[1];
                    inName = "flexe-tunnel"+busiMplstpElement1.getReverseStartPortName().split("mtnveth")[1];
                }
            }else{//宿 只有入端口、入标签 反向出端口  反向出标签  反向下一跳地址
                ip = busiMplstpElement1.getReverseIp();
                outLable = busiMplstpElement1.getReverseEndLabel();

                inLable = busiMplstpElement1.getPositiveStartLabel();

                if (!"veth".equals(busiMplstpElement1.getPortMode())){
                    outName = busiMplstpElement1.getReverseEndPortName();
                    inName = busiMplstpElement1.getPositiveStartPortName();
                }else {
                    outName = "flexe-tunnel"+busiMplstpElement1.getReverseEndPortName().split("mtnveth")[1];
                    inName = "flexe-tunnel"+busiMplstpElement1.getPositiveStartPortName().split("mtnveth")[1];
                }
            }

            String protectActiveXml5 = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "        <static-te-lsps>" +
                    "          <static-te-lsp>" +
                    "            <lsp-name>" + lspName + "</lsp-name>" +//
                    "            <lsp-role>bi-head</lsp-role>" +
                    "            <bi-lsp-type>bi</bi-lsp-type>" +
                    "            <out-segment>" +
                    "              <next-hop>" + ip + "</next-hop>" +//下一跳ip地址
                    "              <out-label>" + outLable + "</out-label>" +//出标签,16..1048575
                    "              <out-ifname>" + outName + "</out-ifname>" +//出端口
                    "            </out-segment>" +
                    "            <in-segment>" +
                    "              <in-label>" + inLable + "</in-label>" +//反向入入标签,16..786432  网元唯一
                    "              <in-ifname>" + inName + "</in-ifname>" +//入端口
                    "            </in-segment>" +
                    "          </static-te-lsp>" +
                    "        </static-te-lsps>" +
                    "<mpls-te/>" +//改属性为空  不能去掉否则报错
                    "</mpls>";
            logger.info("mplsp-lsp相关报文数据protectActiveXml5：" + protectActiveXml5.toString());
            isSend = deviceManager.editConfig(protectActiveXml5, "merge");
            logger.info("mplsp-报文数据protectActiveXml5执行结果=========================================="+isSend);

        }
        //==========================================================查询me ips信息========================
        for (BusiMplstpListVo2 busiMplstpElement1 : listByElement){
            String destIp = "";
            String lspName = "";
            String meName = "";
            //工作
            if ("1".equals(busiMplstpElement1.getRouteType())){
                lspName = busiMplstpElement1.getPositiveLspName();
                meName = workMeName;
            }else {
                lspName = busiMplstpElement1.getReverseLspName();
                meName = proMeName;
            }
            if ("1".equals(entity.getElementType())){
                destIp  = entity.getEndLsrId().substring(entity.getEndLsrId().indexOf("(") + 1, entity.getEndLsrId().indexOf(")"));
            } else if ("2".equals(entity.getElementType())){
                destIp  = entity.getStartLsrId().substring(entity.getStartLsrId().indexOf("(") + 1, entity.getStartLsrId().indexOf(")"));
            }
            String protectActiveXml17 = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "        <mpls-te>" +
                    "          <tunnel-te>" +
                    "            <id>" + busiMplstpElement1.getPositiveTunnelId() + "</id>" +
                    "            <destination-ip>" + destIp + "</destination-ip>" +
                    "            <signal-protocol>static</signal-protocol>" +
                    "            <bi-tunnel>bi</bi-tunnel>" +
                    "            <aps-mode>private</aps-mode>" +
                    "            <static-lsp>" +
                    "              <lsp-type>primary-lsp</lsp-type>" +
                    "              <lsp-bi>bi</lsp-bi>" +
                    "              <lsp-name>"+lspName+"</lsp-name>" +
                    "            </static-lsp>" +
                    "            <vpoams xmlns=\"http://fiberhome.com/fhnw/yang/oam/fos-tpoam\">" +
                    "              <vpoam>" +
                    "                <tunnel-type>primary</tunnel-type>" +
                    "                <me-name>"+meName+"</me-name>" +//  工作名称与oam保持一致
                    "              </vpoam>" +
                    "            </vpoams>" +
                    "          </tunnel-te>" +
                    "        </mpls-te>" +
                    "      </mpls>";
            logger.info("mplsp-me ip报文数据protectActiveXml7：" + protectActiveXml17.toString());
            isSend = deviceManager.editConfig(protectActiveXml17, "merge");
            logger.info("mplsp-报文数据protectActiveXml7执行结果=========================================="+isSend);
        }

        //有且工作保护两条，工作和保护路径同时存在时
        if (listByElement.size()==2){
            String priTunnelId ="";
            String bakTunnelId ="";
            for (BusiMplstpListVo2 busiMplstpElement1 : listByElement){
                if ("1".equals(busiMplstpElement1.getRouteType())){
                    priTunnelId = busiMplstpElement1.getPositiveTunnelId();
                }else {
                    bakTunnelId = busiMplstpElement1.getPositiveTunnelId();
                }
            }
            String boundleId ="";
            if ("1".equals(entity.getElementType())){
                boundleId = entity.getStartTunnelBundleId();
            } else if ("2".equals(entity.getElementType())){
                boundleId = entity.getEndTunnelBundleId();
            }
            String protectActiveXml9 = "  <mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "    <mpls-te>" +
                    "      <tunnel-bundle>" +
                    "        <id>"+boundleId+"</id>" +
                    "        <pri-tunnel-id>"+priTunnelId+"</pri-tunnel-id>" +
                    "        <bak-tunnel-id>"+bakTunnelId+"</bak-tunnel-id>" +
                    "        <revertive-mode>revertive</revertive-mode>" +
                    "        <wtr>5</wtr>" +
                    "        <holdoff-time>0</holdoff-time>" +
                    "        <protect-type>hot-standby</protect-type>" +
                    "      </tunnel-bundle>" +
                    "    </mpls-te>"+
                    " </mpls>";
            logger.info("mplsp-boundleTunnel报文数据protectActiveXml9：" + protectActiveXml9.toString());
            isSend = deviceManager.editConfig(protectActiveXml9, "merge");
            logger.info("mplsp-报文数据protectActiveXml9执行结果=========================================="+isSend);
        }
        return isSend;
    }

    /**
     * 下发源宿有保护-去激活报文
     * @param entity
     */
    private boolean sendProtectInactXml(BusiMplstpListVo2 entity,String elementId,BusiMplsXmlVo busiMplsXmlVo) {
        //==========================================================查询boundleId信息========================
        String boundleId= "";
        if ("1".equals(entity.getElementType())){
            boundleId = entity.getStartTunnelBundleId();
        }else{
            boundleId = entity.getEndTunnelBundleId();
        }
        boolean isSend = true;

        String protectInactiveXml1 = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                "    <mpls-te>" +
                "      <tunnel-bundle nc:operation=\"remove\">" +
                "        <id>"+boundleId+"</id>" +
                "      </tunnel-bundle>" +
                "    </mpls-te>" +
                "</mpls>";
        logger.info("mplsp-boundle去激活报文数据protectInactiveXml1：" + protectInactiveXml1.toString());
        isSend = deviceManager.editConfig(protectInactiveXml1, "merge");
        logger.info("mplsp-boundle去激活报文数据protectInactiveXml1=========================================="+isSend);


        //==========================================================查询tunnel信息========================

        BusiMplstpElement busiMplstpElement = new BusiMplstpElement();
        busiMplstpElement.setMplstpId(entity.getMplstpId());
        busiMplstpElement.setElementId(elementId);
        //正常结果工作、保护2条
        List<BusiMplstpElement> busiMplstpElements = busiMplstpElementService.selectBusiMplstpElementList(busiMplstpElement);
        for (BusiMplstpElement busiMplstpElement1 : busiMplstpElements){
            String protectInactiveTunnelXml = " <mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "    <mpls-te>" +
                    "      <tunnel-te nc:operation=\"remove\">" +
                    "     <id>"+busiMplstpElement1.getPositiveTunnelId()+"</id>" +
                    "      </tunnel-te>" +
                    "    </mpls-te>" +
                    "   </mpls>" ;
            logger.info("mplsp-tunnel去激活报文数据protectInactiveTunnelXml：" + protectInactiveTunnelXml.toString());
            isSend = deviceManager.editConfig(protectInactiveTunnelXml, "merge");
            logger.info("mplsp-tunnel去激活报文数据protectInactiveTunnelXml执行结果=========================================="+isSend);

        }
        for (BusiMplstpElement busiMplstpElement1 : busiMplstpElements){
            String lspName = "";
            if ("1".equals(busiMplstpElement1.getRouteType())){
                lspName = busiMplstpElement1.getPositiveLspName();
            }else {
                lspName = busiMplstpElement1.getReverseLspName();
            }
            //==========================================================查询lspname信息========================

            String protectInactiveXml4 = " <mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "        <static-te-lsps>" +
                    "          <static-te-lsp nc:operation=\"remove\">" +
                    "            <lsp-name>"+lspName+"</lsp-name>" +
                    "            <lsp-role>bi-head</lsp-role>" +
                    "          </static-te-lsp>" +
                    "        </static-te-lsps>" +
                    "        <mpls-te/>" +
                    "      </mpls>" ;
            logger.info("mplsp-去激活lspname报文数据protectInactiveXml4：" + protectInactiveXml4.toString());
            isSend = deviceManager.editConfig(protectInactiveXml4, "merge");
            logger.info("mplsp-报文数据protectInactiveXml4执行结果=========================================="+isSend);
        }
        for (BusiMplstpElement busiMplstpElement1 : busiMplstpElements){
            String protectInactiveXml6 = "   <if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                    "        <interfaces>" +
                    "          <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation=\"remove\">" +
                    "            <name>tunnel"+busiMplstpElement1.getPositiveTunnelId()+"</name>" +
                    "            <type>TUNNEL</type>" +
                    "          </interface>" +
                    "        </interfaces>" +
                    "      </if>" ;
            logger.info("mplsp-去激活tunnel报文数据protectInactiveXml6：" + protectInactiveXml6.toString());
            isSend = deviceManager.editConfig(protectInactiveXml6, "merge");
            logger.info("mplsp-报文数据protectInactiveXml6执行结果=========================================="+isSend);
        }

        //==========================================================查询oam信息========================
        ElementBusiMplsAlarmoam oamParam = new ElementBusiMplsAlarmoam();
        oamParam.setMplstpId(entity.getMplstpId());
        //网元id
        oamParam.setElementId(elementId);
        //正常结果2条
        List<ElementBusiMplsAlarmoamVo> oamList = elementBusiMplsAlarmoamService.selectElementBusiMplsAlarmoamList(oamParam);

        for (ElementBusiMplsAlarmoamVo oam : oamList) {
            String protectInactiveXml8 = "  <tpoam xmlns=\"http://fiberhome.com/fhnw/yang/oam/fos-tpoam\">" +
                    "        <meg-cfg>" +
                    "          <meg-list nc:operation=\"remove\">" +
                    "            <meg-name>"+oam.getMegName()+"</meg-name>" +
                    "           </meg-list>" +
                    "        </meg-cfg>" +
                    "      </tpoam>" ;
            logger.info("mplsp-去激活me报文数据protectInactiveXml8：" + protectInactiveXml8.toString());
            isSend = deviceManager.editConfig(protectInactiveXml8, "merge");
            logger.info("mplsp-报文数据protectInactiveXml8执行结果=========================================="+isSend);
        }
        return isSend;

    }

    /**
     * 下发无保护报文
     *
     * @param entity
     * @param elementId
     * @return
     */
    private boolean sendNoProtectXml(BusiMplstpListVo2 entity, String elementId) {
        BusiMplsXmlVo busiMplsXmlVo = new BusiMplsXmlVo();
        boolean isSend = true;
        //源网元只有对应出信息  前后端达成一致   start为入  end为出
        if ("1".equals(entity.getElementType())) {
            busiMplsXmlVo.setElementId(entity.getStartElement());
            busiMplsXmlVo.setPortName(entity.getPositiveEndPortName());
            busiMplsXmlVo.setInLabel(entity.getReverseStartLabel());
            busiMplsXmlVo.setOutLabel(entity.getPositiveEndLabel());
            busiMplsXmlVo.setDestIp(entity.getEndLsrId().substring(entity.getEndLsrId().indexOf("(") + 1, entity.getEndLsrId().indexOf(")")));
        } else if ("2".equals(entity.getElementType())) {
            busiMplsXmlVo.setElementId(entity.getEndElement());
            busiMplsXmlVo.setPortName(entity.getPositiveStartPortName());
            busiMplsXmlVo.setInLabel(entity.getPositiveStartLabel());
            busiMplsXmlVo.setOutLabel(entity.getReverseEndLabel());
            busiMplsXmlVo.setDestIp(entity.getStartLsrId().substring(entity.getStartLsrId().indexOf("(") + 1, entity.getStartLsrId().indexOf(")")));

        } else if ("3".equals(entity.getElementType())) {
            //过站前置条件为：下发两个接口  两个mpls使能
            BusiMplstpRouteTable routeTable = new BusiMplstpRouteTable();
            routeTable.setMplstpId(entity.getId());
            routeTable.setRouteDirection("1");
            routeTable.setRouteType("1");
            routeTable.setElementId(elementId);
            List<BusiMplstpRouteTableListVo> busiMplstpRouteTableListVos = busiMplstpRouteTableService.selectBusiMplstpRouteTableList(routeTable);
            if (busiMplstpRouteTableListVos.size() > 0) {
                for (BusiMplstpRouteTableListVo busiMplstpRouteTableListVo : busiMplstpRouteTableListVos) {
                    //通过一个过站可以查询到两条路由信息
                    ElementPortMode elementPortMode = elementPortModeService.selectElementPortModeById(busiMplstpRouteTableListVo.getPortId());
                    ElementPortEth elementPortEth = new ElementPortEth();
                    elementPortEth.setElementId(elementPortMode.getElementId());
                    elementPortEth.setPortName(elementPortMode.getPortName());
                    busiMplsXmlVo.setPortName(elementPortMode.getPortName());
                    List<ElementPortEth> elementPortEths = elementPortEthService.selectElementPortEthList(elementPortEth);
                    if (!CollectionUtils.isEmpty(elementPortEths)) {
                        busiMplsXmlVo.setIp(elementPortEths.get(0).getIp());
                        busiMplsXmlVo.setMask(elementPortEths.get(0).getMask());
                        busiMplsXmlVo.setMaxFrameLen(elementPortEths.get(0).getMaxFrameLen());
                        //下发预置条件
                    }
                }
                busiMplsXmlVo.setElementId(busiMplstpRouteTableListVos.get(0).getElementId());

            }
            //激活
            if ("1".equals(entity.getStatus())) {
                //出接口的IP和下一跳是同一个网段  连纤两端的IP必须在一个网段？？？前端限制
                BusiMplstpListVo busiMplstp = new BusiMplstpListVo();
                busiMplstp.setElementId(elementId);
                busiMplstp.setId(entity.getMplstpId());
                List<BusiMplstpListVo2> listByElement = busiMplstpService.selectBusiMplstpEleList2(busiMplstp);
                //只有工作一条
                String actCrossXml = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                        "        <static-te-lsps>" +
                        "          <static-te-lsp>" +
                        "            <lsp-name>" + listByElement.get(0).getPositiveLspName() + "</lsp-name>" +
                        "            <lsp-role>bi-transit</lsp-role>" +
                        "            <bi-lsp-type>bi</bi-lsp-type>" +
                        "            <out-segment>" +
                        "              <next-hop>" + listByElement.get(0).getPositiveIp() + "</next-hop>" +
                        "              <out-label>"+listByElement.get(0).getPositiveEndLabel()+"</out-label>" ;
                        if(!listByElement.get(0).getPositiveEndPortName().startsWith("mtnveth")){
                            actCrossXml+="<out-ifname>" + listByElement.get(0).getPositiveEndPortName() + "</out-ifname>";
                        }else{
                            String mtnNum = listByElement.get(0).getPositiveEndPortName().split("mtnveth")[1];
                            actCrossXml+="              <out-ifname>flexe-tunnel" + mtnNum + "</out-ifname>" ;
                        }

                actCrossXml+="            </out-segment>" +
                        "            <in-segment>" +
                        "              <in-label>"+listByElement.get(0).getPositiveStartLabel()+"</in-label>";
                if(!listByElement.get(0).getPositiveStartPortName().startsWith("mtnveth")){
                    actCrossXml+="              <in-ifname>" + listByElement.get(0).getPositiveStartPortName() + "</in-ifname>";
                }else{
                    String mtnNum = listByElement.get(0).getPositiveStartPortName().split("mtnveth")[1];
                    actCrossXml+="              <in-ifname>flexe-tunnel" + mtnNum + "</in-ifname>" ;
                }

                actCrossXml+= "            </in-segment>" +
                        "            <reverse-in-segment>" +
                        "              <in-label>"+listByElement.get(0).getReverseStartLabel()+"</in-label>" ;
                if(!listByElement.get(0).getReverseStartPortName().startsWith("mtnveth")){
                    actCrossXml+="              <in-ifname>" + listByElement.get(0).getReverseStartPortName() + "</in-ifname>";
                }else{
                    String mtnNum = listByElement.get(0).getReverseStartPortName().split("mtnveth")[1];
                    actCrossXml+="              <in-ifname>flexe-tunnel" + mtnNum + "</in-ifname>" ;
                }

                actCrossXml+="            </reverse-in-segment>" +
                        "            <reverse-out-segment>" +
                        "              <next-hop>" + listByElement.get(0).getReverseIp() + "</next-hop>" +
                        "              <out-label>"+listByElement.get(0).getReverseEndLabel()+"</out-label>";
                if(!listByElement.get(0).getReverseEndPortName().startsWith("mtnveth")){
                    actCrossXml+= "              <out-ifname>" + listByElement.get(0).getReverseEndPortName() + "</out-ifname>";
                }else{
                    String mtnNum = listByElement.get(0).getReverseEndPortName().split("mtnveth")[1];
                    actCrossXml+="              <out-ifname>flexe-tunnel" + mtnNum + "</out-ifname>" ;
                }

                actCrossXml+="            </reverse-out-segment>" +
                        "          </static-te-lsp>" +
                        "        </static-te-lsps>" +
                        "        <mpls-te/>" +
                        "      </mpls>";
                logger.info("mplsp-无保护-过站激活报文数据actCrossXml：" + actCrossXml.toString());
                 isSend = deviceManager.editConfig(actCrossXml, "merge");
                 return isSend;
            } else {
                //去激活
                String unActCrossXml = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                        "        <static-te-lsps>" +
                        "          <static-te-lsp nc:operation=\"remove\">" +
                        "            <lsp-name>" + entity.getPositiveLspName() + "</lsp-name>" +
                        "            <lsp-role>bi-transit</lsp-role>" +//过站transit  源宿head
                        "            <bi-lsp-type>bi</bi-lsp-type>" +
                        "          </static-te-lsp>" +
                        "        </static-te-lsps>" +
                        "        <mpls-te/>" +
                        "      </mpls>";
                logger.info("mplsp-无保护-过站去激活报文数据unActCrossXml：" + unActCrossXml.toString());
                 isSend = deviceManager.editConfig(unActCrossXml, "merge");
                return isSend;
            }
        }
        //查询 ip mask
        ElementPortEth elementPortEth = new ElementPortEth();
        elementPortEth.setElementId(busiMplsXmlVo.getElementId());
        elementPortEth.setPortName(busiMplsXmlVo.getPortName());
        List<ElementPortEth> elementPortEths = elementPortEthService.selectElementPortEthList(elementPortEth);
        if (!CollectionUtils.isEmpty(elementPortEths)) {
            busiMplsXmlVo.setIp(elementPortEths.get(0).getIp());
            busiMplsXmlVo.setMask(elementPortEths.get(0).getMask());
            busiMplsXmlVo.setMaxFrameLen(elementPortEths.get(0).getMaxFrameLen());

        }
        //前后端达成一致   start为入  end为出
        //1对于源网元，只有源端口源标签，有正向下一跳地址，无反向下一跳地址；出端口、出标签从路由表中获取
        //2对于宿网元，只有宿端口宿标签，无正向下一跳地址，有反向下一跳地址；出端口、出标签从路由表中获取
        //查询下一跳地址
        if ("1".equals(entity.getElementType())) {
            busiMplsXmlVo.setNextIp(entity.getPositiveIp());
        } else if ("2".equals(entity.getElementType())) {
            busiMplsXmlVo.setNextIp(entity.getReverseIp());
        }
        //激活
        if ("1".equals(entity.getStatus())) {
            String mtnNum ="";
            if ("veth".equals(entity.getPortMode())){
                //对于源网元 取出端口
                mtnNum = busiMplsXmlVo.getPortName().split("mtnveth")[1];
            }
                if (!"veth".equals(entity.getPortMode())){
                    //2.14修改可成功下发
                    String xml2 = "   <mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                            "        <mpls-te>" +
                            "          <interface>" +//网元管理器-以太主接口-MPLS使能设置为使能
                            "            <ifname>" + busiMplsXmlVo.getPortName() + "</ifname>" +//tunnel的服务层L3LINK的端口
                            "          </interface>" +
                            "        </mpls-te>" +
                            "    </mpls>";
                    boolean isSend2 = deviceManager.editConfig(xml2, "merge");
                    logger.info("mplsp报文数据xml2：" + xml2.toString());
                    logger.info("isSend2结果===================================================：" + isSend2);
                }

                //1、tunnel下发，源网元,生成tunnel口
                String xml3 = "    <if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "        <interfaces>" +
                        "          <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "            <name>tunnel" + entity.getPositiveTunnelId() + "</name>" +//从主表获取
                        "            <type>TUNNEL</type>" +
                        "          </interface>" +
                        "        </interfaces>" +
                        "      </if>";
                logger.info("mplsp报文数据xml3：" + xml3.toString());//单下和一起下都展示日志
                boolean isSend3 = deviceManager.editConfig(xml3, "merge");
                logger.info("isSend3结果===================================================：" + isSend3);
                //2、静态LSP实例配置
                String xml4 = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                        "        <static-te-lsps>" +
                        "          <static-te-lsp>" +
                        "            <lsp-name>" + entity.getPositiveLspName() + "</lsp-name>" +
                        "            <lsp-role>bi-head</lsp-role>" +
                        "            <bi-lsp-type>bi</bi-lsp-type>" +
                        "            <out-segment>" +
                        "              <next-hop>" + busiMplsXmlVo.getNextIp() + "</next-hop>" +//下一跳ip地址
                        "              <out-label>" + busiMplsXmlVo.getOutLabel() + "</out-label>" ;//出标签,16..1048575
                if (!"veth".equals(entity.getPortMode())){
                    xml4+="              <out-ifname>" + busiMplsXmlVo.getPortName() + "</out-ifname>";//出端口
                }else{
                    xml4+="              <out-ifname>flexe-tunnel" + mtnNum + "</out-ifname>" ;//入端口
                }
                    xml4+="            </out-segment>" +
                        "            <in-segment>" +
                        "              <in-label>" + busiMplsXmlVo.getInLabel() + "</in-label>";//入标签,16..786432  网元唯一
                if (!"veth".equals(entity.getPortMode())){
                    xml4+="              <in-ifname>" + busiMplsXmlVo.getPortName() + "</in-ifname>";//入端口
                }else{
                    xml4+="              <in-ifname>flexe-tunnel" + mtnNum + "</in-ifname>" ;//入端口
                }

                    xml4+="            </in-segment>" +
                        "          </static-te-lsp>" +
                        "        </static-te-lsps>" +
                        "<mpls-te/>" +//改属性为空  不能去掉否则报错
                        "</mpls>";
                logger.info("mplsp报文数据xml4：" + xml4.toString());//单下和一起下都展示日志
                boolean isSend4 = deviceManager.editConfig(xml4, "merge");
                logger.info("isSend4结果===================================================：" + isSend4);
                //3、MPLS-TE配置
                String xml5 = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                        "        <mpls-te>" +
                        "          <tunnel-te>" +
                        "            <id>" + entity.getPositiveTunnelId() + "</id>" +//从主表信息获取
                        "            <protect-type>no-protect</protect-type>" + //hot-standby
                        "            <destination-ip>" + busiMplsXmlVo.getDestIp() + "</destination-ip>" +//连纤对端端口IP
                        "            <signal-protocol>static</signal-protocol>" +
                        "            <bi-tunnel>bi</bi-tunnel>" +
                        "            <static-lsp>" +
                        "              <lsp-type>primary-lsp</lsp-type>" +
                        "              <lsp-bi>bi</lsp-bi>" +
                        "              <lsp-name>" + entity.getPositiveLspName() + "</lsp-name>" +
                        "            </static-lsp>" +
                        "          </tunnel-te>" +
                        "        </mpls-te>" +
                        "      </mpls>";
                logger.info("mplsp报文数据xml5：" + xml5.toString());//单下和一起下都展示日志
                boolean isSend5 = deviceManager.editConfig(xml5, "merge");
                logger.info("isSend5结果===================================================：" + isSend5);
                return isSend5;

            //去激活
        } else {
            //3、MPLS-TE配置
            String xml5 = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "        <mpls-te>" +
                    "          <tunnel-te nc:operation=\"remove\">" +
                    "            <id>" + entity.getPositiveTunnelId() + "</id>" +//从主表信息获取
                    "          </tunnel-te>" +
                    "        </mpls-te>" +
                    "      </mpls>";
            logger.info("mplsp去激活报文数据xml5：" + xml5.toString());//单下和一起下都展示日志
            boolean isSend5 = deviceManager.editConfig(xml5, "merge");
            logger.info("isSend5结果===================================================：" + isSend5);

            //2、静态LSP实例配置
            String xml4 = "<mpls xmlns=\"http://fiberhome.com/fhnw/yang/mplsprotocol/fos-mpls\">" +
                    "        <static-te-lsps>" +
                    "          <static-te-lsp nc:operation=\"remove\">" +
                    "            <lsp-name>" + entity.getPositiveLspName() + "</lsp-name>" +
                    "            <lsp-role>bi-head</lsp-role>" +
                    "          </static-te-lsp>" +
                    "        </static-te-lsps>" +
                    "<mpls-te/>" +//改属性为空  不能去掉否则报错
                    "</mpls>";
            logger.info("mplsp去激活报文数据xml4：" + xml4.toString());//单下和一起下都展示日志
            boolean isSend4 = deviceManager.editConfig(xml4, "merge");
            logger.info("isSend4结果===================================================：" + isSend4);
            //1、tunnel下发，源网元,生成tunnel口
            String xml3 = "    <if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                    "        <interfaces>" +
                    "          <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\" nc:operation = \"remove\">" +
                    "            <name>tunnel" + entity.getPositiveTunnelId() + "</name>" +//从主表获取
                    "            <type>TUNNEL</type>" +
                    "          </interface>" +
                    "        </interfaces>" +
                    "      </if>";
            logger.info("mplsp报文数据xml3：" + xml3.toString());//单下和一起下都展示日志
            boolean isSend3 = deviceManager.editConfig(xml3, "merge");
            logger.info("isSend3结果===================================================：" + isSend3);
            return isSend3;
        }

    }

}
